package com.liaoyin.travel.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.liaoyin.travel.entity.DictBasic;
import com.liaoyin.travel.service.DictBasicService;

import java.util.List;

/**
 * 数据字典工具类
 */
@Component
public class DictUtil {

    private static DictBasicService dictBasicService;

    @Autowired
    public void setDictBasicService(DictBasicService dictBasicService) {
        DictUtil.dictBasicService = dictBasicService;
    }

    /**
     * 通过数据字典code跟value读取display显示值
     *
     * @param code  code
     * @param value value
     * @return string
     */
    public static String getDisplay(String code, String value) {
        if (StringUtils.isBlank(code) || StringUtils.isBlank(value) || "null".equals(value)) {
            return null;
        }

        String result = "";

        List<DictBasic> dictList = dictBasicService.selectDictByCode(code);
        for (DictBasic dictBasic : dictList) {
            if (value.equals(String.valueOf(dictBasic.getValue()))) {
                result = dictBasic.getDisplay();
                break;
            }
        }
        return result;
    }

    /**
     * 通过数据字典code跟value读取display显示值
     *
     * @param code  code
     * @param value value 多个值以逗号分隔
     * @return string
     */
    public static String getDisplayByMoreValue(String code, String value) {
        if (StringUtils.isBlank(code) || StringUtils.isBlank(value) || "null".equals(value)) {
            return null;
        }
        String result = "";
        List<DictBasic> dictList = dictBasicService.selectDictByCode(code);
        String [] valueList = value.split(",");
        for (DictBasic dictBasic : dictList) {
            for(int i=0;i<valueList.length;i++) {
                if (valueList[i].equals(dictBasic.getValue())) {
                    result = result+dictBasic.getDisplay()+"、";
                }
            }
        }
        if(result.length()>0){
            result = result.substring(0,result.length()-1);
        }
        return result;
    }

    public static String getValueForDisplay(String display){
        String value="";
        List<DictBasic> dictBasics = dictBasicService.selectDictByDisplay(display);
        for (DictBasic dictBasic : dictBasics) {
            value = dictBasic.getValue()+"";
        }
        return value;
    }

    //刷新数据字典缓存
    public static void refreshDict(){
        dictBasicService.flushDictCache();
    }
}
